//
//  AddChildViewController.m
//  IpadTestB
//
//  Created by edianzu on 2017/7/5.
//  Copyright © 2017年 ruilai. All rights reserved.
//

#import "AddChildViewController.h"
#import "ChooseWayCell.h"
#import "ChoosePersonCell.h"
@interface AddChildViewController ()<UITableViewDataSource,UITableViewDelegate>
@property (nonatomic,strong) ClassModel * rightNowClassModel;
@property (nonatomic,strong) NSMutableArray * rightArray;
@property (nonatomic,strong) NSMutableDictionary * allDataDictionary;
@property (nonatomic,assign) NSInteger rightNowInteger;
@property (nonatomic,strong) NSNumber * proid;//用于营销场景
@end

@implementation AddChildViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"选择成员";
    self.view.backgroundColor = UIColorFromRGB(241, 246, 248);
    [self.navigationController.navigationBar setTitleTextAttributes:
     @{NSFontAttributeName:[UIFont boldSystemFontOfSize:23*AutoScaleHorizontal],
       NSForegroundColorAttributeName:[UIColor whiteColor]}];
    ////////////////左按钮
    UIButton * leftBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    leftBtn.frame = CGRectMake(0, 0, 35,35);
    [leftBtn setBackgroundImage:[UIImage imageNamed:@"navBack"] forState:UIControlStateNormal];
    [leftBtn addTarget:self action:@selector(leftBarBtnClicked) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem * leftBarBtn = [[UIBarButtonItem alloc]initWithCustomView:leftBtn];;
    //创建UIBarButtonSystemItemFixedSpace
    UIBarButtonItem * spaceItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
    //将宽度设为负值
    spaceItem.width = 15;
    //将两个BarButtonItem都返回给NavigationItem
    self.navigationItem.leftBarButtonItems = @[spaceItem,leftBarBtn];
    
    //创建右边按钮
    UIButton * rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    rightBtn.frame = CGRectMake(0, 0, 140,35);
    //    [rightBtn setImage:[UIImage imageNamed:@"navRightBtn"] forState:UIControlStateNormal];
    [rightBtn setTitle:@"确定" forState:UIControlStateNormal];
    rightBtn.titleLabel.font = [UIFont systemFontOfSize:20*AutoScaleHorizontal];
    [rightBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [rightBtn addTarget:self action:@selector(rightBarBtnClicked) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem * rightBarBtn = [[UIBarButtonItem alloc]initWithCustomView:rightBtn];;
    //创建UIBarButtonSystemItemFixedSpace
    UIBarButtonItem * spaceItemm = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
    //将宽度设为负值
    spaceItemm.width = -5;
    //将两个BarButtonItem都返回给NavigationItem
    self.navigationItem.rightBarButtonItems = @[spaceItemm,rightBarBtn];
    
    
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if ([self.isFromSale isEqualToString:@"1"]) {
        [self getDataFromSale];
    }else{
        [self getDataFromUnSale];
    }
}

-(void)getDataFromSale{
    self.dataArray = [[NSMutableArray alloc]initWithCapacity:0];
    self.rightNowDataArray = [[NSMutableArray alloc]initWithCapacity:0];//当前展示的数据
    self.schoolNameArr = [[NSMutableArray alloc]initWithCapacity:0];
    //获取全部数据
    NSUserDefaults * user = [NSUserDefaults standardUserDefaults];
    NSString* str = [user objectForKey:@"AllData"];
    NSData *jsonData = [str dataUsingEncoding:NSUTF8StringEncoding];
    _allDataDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil];
    NSMutableArray * testArray = [NSMutableArray arrayWithArray: [_allDataDictionary objectForKey:@"TestResult"]];//有结果的数据
    NSMutableArray * proArr  = [[NSMutableArray alloc]init];
    proArr = [_allDataDictionary objectForKey:@"Programs"];//营销计划的数据 用type+id判断
    _proid = [[NSNumber alloc]init];
    for (NSMutableDictionary * dic in proArr) {
        if ([[dic objectForKey:@"Type"]isEqual:@0]) {
            _proid = [dic objectForKey:@"Id"]; //取得营销计划的ID
        }
    }
    
//    //    //冒泡时间倒叙
//    for (int  i =0; i<[testArray count]-1; i++) {
//        
//        for (int j = i+1; j<[testArray count]; j++) {
//            NSMutableDictionary * dictx = testArray[i];
//            NSMutableDictionary * dict = [dictx objectForKey:@"master"];
//            
//            NSMutableDictionary * dictxx = testArray[j];
//            NSMutableDictionary * dict1 = [dictxx objectForKey:@"master"];
//            if ([[dict objectForKey:@"Id"]integerValue]<[[dict1 objectForKey:@"Id"]integerValue]) {
//                //交换
//                [testArray exchangeObjectAtIndex:i withObjectAtIndex:j];
//            }
//            
//        }
//        
//    }
    //将负数放在最前面
    for (NSMutableDictionary * dict in testArray.reverseObjectEnumerator) {
        NSMutableDictionary * dic = [dict objectForKey:@"master"];
        if ([[dic objectForKey:@"Id"]integerValue]<0) {
            [testArray removeObject:dict];
            [testArray insertObject:dict atIndex:0];
        }
    }

    
//    NSLog(@"%@",[user objectForKey:@"finalSaleDic"]);//已经确定在营销计划的孩子 用于判断SELECT = 1；
    if ([user objectForKey:@"finalSaleDic"] != nil) {//如果有已经确定的孩子， 那么这些孩子默认选中
        NSString * FS = [user objectForKey:@"finalSaleDic"];
        NSData * jsonData = [FS dataUsingEncoding:NSUTF8StringEncoding];
        NSMutableDictionary * mdic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil];
        NSMutableArray * marr = [mdic objectForKey:@"finalSaleDic"];
        
            
            for (NSMutableDictionary * dic in testArray) {
                NSMutableDictionary * masterdic = [dic objectForKey:@"master"];
                if ([[masterdic objectForKey:@"ProgramId"]isEqual:_proid]) {
                    [masterdic setObject:@"0" forKey:@"isSelected"];
                
                for (NSNumber* numId in marr) {
                    if ([[masterdic objectForKey:@"Id"] isEqual: numId]) {
                    [masterdic setObject:@"1" forKey:@"isSelected"];
                }
            }
                ChildModel * model = [ChildModel modelWithDictionary:masterdic];
                [self.rightNowDataArray addObject:model];
                }
        }
    }else{//如果没有已经确定的孩子 ， 全部默认不选中
    
    
   
    
    for (NSMutableDictionary * dict in testArray) {
        NSMutableDictionary * dic = [dict objectForKey:@"master"];
        if ([[dic objectForKey:@"ProgramId"]isEqual:_proid]) {
            [dic setObject:@"0" forKey:@"isSelected"];
            ChildModel * mod = [ChildModel modelWithDictionary:dic];
            [self.rightNowDataArray addObject:mod];
        }
    }
    }
    //默认班级
//    self.rightNowClassModel = self.schoolNameArr[0];
    [self creatUI];
}

-(void)getDataFromUnSale{
    self.dataArray = [[NSMutableArray alloc]initWithCapacity:0];
    self.rightNowDataArray = [[NSMutableArray alloc]initWithCapacity:0];//当前展示的数据
    self.schoolNameArr = [[NSMutableArray alloc]initWithCapacity:0];
    NSUserDefaults * user = [NSUserDefaults standardUserDefaults];
    //获取全部数据
    NSString* str = [user objectForKey:@"AllData"];
    NSData *jsonData = [str dataUsingEncoding:NSUTF8StringEncoding];
    _allDataDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil];
    //班级
    NSMutableArray * allClassArr  = [[NSMutableArray alloc]init];
    allClassArr = [_allDataDictionary objectForKey:@"ClassList"];
    NSMutableDictionary * weifenbanDic = [[NSMutableDictionary alloc]init];
    //将未分班放在第一位
    for (NSMutableDictionary * dic in allClassArr.reverseObjectEnumerator) {
        if ([[dic objectForKey:@"Name"]isEqualToString:@"未分班"]) {
            weifenbanDic =[NSMutableDictionary dictionaryWithDictionary:dic];
            [allClassArr removeObject:dic];
            
        }
        
    }
    [allClassArr insertObject:weifenbanDic atIndex:0];
    for (NSMutableDictionary * dic in allClassArr) {
        ClassModel * mod = [ClassModel modelWithDictionary:dic];
        [self.schoolNameArr addObject:mod];
    }
    //人员以班级为单位筛选
    
    NSMutableArray * testArray = [NSMutableArray arrayWithArray: [_allDataDictionary objectForKey:@"ChildList"]];
    NSMutableArray * masterArray = [NSMutableArray arrayWithArray:[_allDataDictionary objectForKey:@"TestResult"]];
    NSLog(@"%@  ownid",self.ownModel.Id);
    
    for (ClassModel * mod in self.schoolNameArr) {//循环班级
        NSMutableArray * smallArray = [[NSMutableArray alloc]init];//每个班级放一个数组
    for (NSMutableDictionary * dict in testArray) {//循环孩子放入班级数组中
        if ([[dict objectForKey:@"ClassId"]isEqual:mod.Id]) {
            [dict setObject:@"0" forKey:@"isSelected"];
            for (NSMutableDictionary * dic in masterArray) {//查找MASTER 看这个孩子之前有没有参与这个计划
                NSMutableDictionary * masterDic = [dic objectForKey:@"master"];
                if ([[dict objectForKey:@"Id"]isEqual:[masterDic objectForKey:@"ChildId"]]) {
                    if ([[masterDic objectForKey:@"ProgramId"]isEqual:self.ownModel.Id]) {
                        [dict setObject:@"1" forKey:@"isSelected"];
                    }
                }
            }
            ChildModel * model = [ChildModel modelWithDictionary:dict];
            [smallArray addObject:model];
            
                                                             }
    }
        [self.dataArray addObject:smallArray];
    }
    //默认班级
    self.rightNowClassModel = self.schoolNameArr[0];
    self.rightNowDataArray = self.dataArray[0];
    self.rightNowInteger = 0;
    [user synchronize];
    [self creatUI];
}

-(void)creatUI{
    self.myTableView = [[UITableView alloc]init];
    self.myTableView.backgroundColor =UIColorFromRGB(241, 244, 248);
    self.myTableView.delegate =self;
    self.myTableView.dataSource =self;
    self.myTableView.showsVerticalScrollIndicator =NO;
    //无分割线
//    self.myTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    //多余的CELL 隐藏
    self.myTableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    [self.myTableView registerClass:[ChooseWayCell class] forCellReuseIdentifier:@"ChooseWayCell"];
    [self.myTableView registerClass:[ChoosePersonCell class] forCellReuseIdentifier:@"ChoosePersonCell"];
    [self.view addSubview:self.myTableView];
    [self.myTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.view.mas_left).with.offset(75*AutoScaleHorizontal);
        make.top.mas_equalTo(self.view.mas_top).with.offset(20*AutoScaleVertical);
        make.width.mas_equalTo(200*AutoScaleHorizontal);
        make.bottom.mas_equalTo(self.view.mas_bottom).with.offset(-20*AutoScaleVertical);
//        if ([_isFromSale isEqualToString:@"0"]) {
//            make.size.mas_equalTo(CGSizeMake(200*AutoScaleHorizontal, (70*self.rightNowDataArray.count+235)*AutoScaleHorizontal));
//        }else{
//            make.size.mas_equalTo(CGSizeMake(200*AutoScaleHorizontal, (70*self.rightNowDataArray.count+180)*AutoScaleHorizontal));
//        }
        
    }];
    //选择班级隐藏视图
    NSInteger taga = 0;
        UIWindow * window = [UIApplication sharedApplication].keyWindow;
    self.newwView = [[UIScrollView alloc]init];
    self.newwView.backgroundColor = [UIColor clearColor];
    [window addSubview:self.newwView];
    [window bringSubviewToFront:self.newwView];
    [self.newwView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(window.mas_top).with.offset(210*AutoScaleVertical);
        make.left.mas_equalTo(window.mas_left).with.offset(100*AutoScaleHorizontal);
        make.size.mas_equalTo(CGSizeMake(150*AutoScaleHorizontal, 240*AutoScaleVertical));
    }];
    for (ClassModel * mod in self.schoolNameArr) {
        UIButton * btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.layer.borderWidth =1;
        btn.layer.borderColor = UIColorFromRGB(188, 188, 188).CGColor;
        [btn setTitle:mod.Name forState:UIControlStateNormal];
        btn.titleLabel.font = [UIFont systemFontOfSize:18*AutoScaleHorizontal];
        [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        btn.backgroundColor = UIColorFromRGB(26, 167, 157);
        btn.tag = 1000+taga;
        [btn addTarget:self action:@selector(chooseClassWithSender:) forControlEvents:UIControlEventTouchUpInside];
        [self.newwView addSubview:btn];
        [btn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(self.newwView.mas_top).with.offset(taga*30*AutoScaleVertical);
            make.left.mas_equalTo(self.newwView.mas_left);
            make.size.mas_equalTo(CGSizeMake(150*AutoScaleHorizontal, 30*AutoScaleVertical));
        }];
        
        taga++;
    }
    self.newwView.contentSize = CGSizeMake(0, 30*self.schoolNameArr.count);
    self.newwView.hidden =YES;
    
    [self setRightView];

}
//创建右侧视图
-(void)setRightView{
    
    if ([_isFromSale isEqualToString:@"0"]) {//非营销进入的UI
        
    
    self.rightArray = [[NSMutableArray alloc]init];
    for (NSMutableArray* arr in self.dataArray) {
        for (ChildModel * mod in arr) {
            [self.rightArray addObject:mod];
        }
    }
    
    //右侧需要多少行
        NSInteger neednum = 0;
        for (ChildModel * mod in self.rightArray) {
            if ([mod.isSelected isEqualToString: @"1"]) {
                neednum +=1;
            }
        }
    if (neednum / 3 ==0) {
        self.rightLines = neednum/3;
    }else{
        self.rightLines = neednum/3 + 1;
    }
    //右侧VIEW
    self.rightView = [[UIScrollView alloc]init];
    self.rightView.layer.cornerRadius =10;
    self.rightView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.rightView];
    [self.rightView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.myTableView.mas_right).with.offset(30*AutoScaleHorizontal);
        make.top.mas_equalTo(self.view.mas_top).with.offset(30*AutoScaleVertical);
        make.width.mas_equalTo(600*AutoScaleHorizontal);
        make.bottom.mas_equalTo(self.view.mas_bottom).with.offset(-20*AutoScaleVertical);
        
    }];
    
    self.alreadyChoseLabel = [[UILabel alloc]init];
    self.alreadyChoseLabel.font = [UIFont boldSystemFontOfSize:23*AutoScaleHorizontal];
    self.alreadyChoseLabel.textColor = [UIColor blackColor];
    NSInteger alreadyChose = 0;
    for (ChildModel * mod in self.rightArray) {
        if ([mod.isSelected isEqualToString: @"1"]) {
            alreadyChose +=1;
        }
    }
    self.alreadyChoseLabel.text = [NSString stringWithFormat:@"已选学员%d人",alreadyChose];
    [self.rightView addSubview:self.alreadyChoseLabel];
    [self.alreadyChoseLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.rightView.mas_left).with.offset(50*AutoScaleHorizontal);
        make.top.mas_equalTo(self.rightView.mas_top).with.offset(40*AutoScaleVertical);
        make.size.mas_equalTo(CGSizeMake(330*AutoScaleHorizontal, 20*AutoScaleVertical));
    }];
    
    //带文字和图片的按钮
    NSInteger a = 0;
    for (ChildModel * mod in self.rightArray) {
        if ([mod.isSelected isEqualToString:@"1"]) {
            UIButton * probtn = [UIButton buttonWithType:UIButtonTypeCustom];
            probtn.layer.cornerRadius = 10;
            probtn.backgroundColor =UIColorFromRGB(26, 167, 157);
            probtn.tag = a + 200;
            [probtn setTitle:mod.ChildName forState:UIControlStateNormal];
            [probtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            probtn.titleLabel.font = [UIFont systemFontOfSize:20*AutoScaleHorizontal];
            //设置按钮图片在上文字在下
            probtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
            probtn.titleEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0);
            [probtn addTarget:self action:@selector(cancelChoose:) forControlEvents:UIControlEventTouchUpInside];
            [self.rightView addSubview:probtn];
            [probtn mas_remakeConstraints:^(MASConstraintMaker *make) {
                make.left.mas_equalTo(self.rightView.mas_left).with.offset((50+175*(a%3))*AutoScaleHorizontal);
                make.top.mas_equalTo(self.rightView.mas_top).with.offset((100+55*(a/3)*AutoScaleVertical));
                make.size.mas_equalTo(CGSizeMake(150*AutoScaleHorizontal, 40*AutoScaleVertical));
        }];
            
            UILabel * Ximg = [[UILabel alloc]init];
            Ximg.textColor = [UIColor whiteColor];
            Ximg.font = [UIFont systemFontOfSize:20];
            Ximg.text=@"X";
            [probtn addSubview:Ximg];
            [Ximg mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerY.mas_equalTo(probtn.mas_centerY);
                make.right.mas_equalTo(probtn.mas_right).with.offset(5*AutoScaleHorizontal);
                make.size.mas_equalTo(CGSizeMake(25*AutoScaleHorizontal, 25*AutoScaleVertical));
            }];
            a++;
        }

//        //右侧需要多少行
//        NSInteger neednum = 0;
//        for (ChildModel * mod in self.rightArray) {
//            if ([mod.isSelected isEqualToString: @"1"]) {
//                neednum +=1;
//            }
//        }
//        if (neednum / 3 ==0) {
//            self.rightLines = neednum/3;
//        }else{
//            self.rightLines = neednum/3 + 1;
//        }
        
    }
        self.rightView.contentSize = CGSizeMake(0, (200+40*self.rightLines+(15*(self.rightLines-1)))*AutoScaleVertical);
    }else{//从营销进来
        
        //右侧需要多少行
        NSInteger alreadyChose = 0;
        for (ChildModel * mod in self.rightNowDataArray) {
            if ([mod.isSelected isEqualToString: @"1"]) {
                alreadyChose +=1;
            }
        }
        if (alreadyChose / 3 ==0) {
            self.rightLines = alreadyChose/3;
        }else{
            self.rightLines = alreadyChose/3 + 1;
        }
        //右侧VIEW
        self.rightView = [[UIScrollView alloc]init];
        self.rightView.layer.cornerRadius =10;
        self.rightView.backgroundColor = [UIColor whiteColor];
        [self.view addSubview:self.rightView];
        [self.rightView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(self.myTableView.mas_right).with.offset(30*AutoScaleHorizontal);
            make.top.mas_equalTo(self.view.mas_top).with.offset(30*AutoScaleVertical);
            make.width.mas_equalTo(600*AutoScaleHorizontal);
            make.bottom.mas_equalTo(self.view.mas_bottom).with.offset(-20*AutoScaleVertical);
            
        }];
        
        self.alreadyChoseLabel = [[UILabel alloc]init];
        self.alreadyChoseLabel.font = [UIFont boldSystemFontOfSize:23*AutoScaleHorizontal];
        self.alreadyChoseLabel.textColor = [UIColor blackColor];
        
        self.alreadyChoseLabel.text = [NSString stringWithFormat:@"已选学员%d人",alreadyChose];
        [self.rightView addSubview:self.alreadyChoseLabel];
        [self.alreadyChoseLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(self.rightView.mas_left).with.offset(50*AutoScaleHorizontal);
            make.top.mas_equalTo(self.rightView.mas_top).with.offset(40*AutoScaleVertical);
            make.size.mas_equalTo(CGSizeMake(330*AutoScaleHorizontal, 20*AutoScaleVertical));
        }];
        
        //带文字和图片的按钮
        NSInteger a = 0;
        for (ChildModel * mod in self.rightNowDataArray) {
            if ([mod.isSelected isEqualToString:@"1"]) {
                UIButton * probtn = [UIButton buttonWithType:UIButtonTypeCustom];
                probtn.layer.cornerRadius = 10;
                probtn.backgroundColor =UIColorFromRGB(26, 167, 157);
                probtn.tag = a + 200;
                [probtn setTitle:mod.ChildName forState:UIControlStateNormal];
                [probtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
                probtn.titleLabel.font = [UIFont systemFontOfSize:20*AutoScaleHorizontal];
                //设置按钮图片在上文字在下
                probtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
                probtn.titleEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0);
                [probtn addTarget:self action:@selector(cancelChoose:) forControlEvents:UIControlEventTouchUpInside];
                [self.rightView addSubview:probtn];
                [probtn mas_remakeConstraints:^(MASConstraintMaker *make) {
                    make.left.mas_equalTo(self.rightView.mas_left).with.offset((50+175*(a%3))*AutoScaleHorizontal);
                    make.top.mas_equalTo(self.rightView.mas_top).with.offset((100+55*(a/3)*AutoScaleVertical));
                    make.size.mas_equalTo(CGSizeMake(150*AutoScaleHorizontal, 40*AutoScaleVertical));
                }];
                
                UILabel * Ximg = [[UILabel alloc]init];
                Ximg.textColor = [UIColor whiteColor];
                Ximg.font = [UIFont systemFontOfSize:20];
                Ximg.text=@"X";
                [probtn addSubview:Ximg];
                [Ximg mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.centerY.mas_equalTo(probtn.mas_centerY);
                    make.right.mas_equalTo(probtn.mas_right).with.offset(5*AutoScaleHorizontal);
                    make.size.mas_equalTo(CGSizeMake(25*AutoScaleHorizontal, 25*AutoScaleVertical));
                }];
                a++;
            }
        }
//        //右侧需要多少行
//        NSInteger alreadyChose = 0;
//        for (ChildModel * mod in self.rightNowDataArray) {
//            if ([mod.isSelected isEqualToString: @"1"]) {
//                alreadyChose +=1;
//            }
//        }
//        if (alreadyChose / 3 ==0) {
//            self.rightLines = alreadyChose/3;
//        }else{
//            self.rightLines = alreadyChose/3 + 1;
//        }
        self.rightView.contentSize = CGSizeMake(0, (200+40*self.rightLines+(15*(self.rightLines-1)))*AutoScaleVertical);
//        make.size.mas_equalTo(CGSizeMake(600*AutoScaleHorizontal, (200+40*self.rightLines+(15*(self.rightLines-1)))*AutoScaleVertical));
    }
}

#pragma mark tableViewDelegate
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row ==0) {
        if ([self.isFromSale isEqualToString:@"0"]) {
            return 205*AutoScaleVertical;
        }else{
        return 150*AutoScaleVertical;
        }
    }else{
        
    
    return 70*AutoScaleVertical;
    }
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.rightNowDataArray.count+1;
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSMutableArray * masterArray = [NSMutableArray arrayWithArray:[_allDataDictionary objectForKey:@"TestResult"]];
    if (indexPath.row == 0) {
        ChooseWayCell * cell = [tableView dequeueReusableCellWithIdentifier:@"ChooseWayCell"];
        if (cell ==nil) {
            cell = [[ChooseWayCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"ChooseWayCell"];
        }
        NSInteger isall = 1;
        for (ChildModel * mod in self.rightNowDataArray) {
            if (![mod.isSelected isEqualToString:@"1"]) {
                isall+=1;//当有未选择的MODEL时  ISALL + 1； 判断是否全选
            }
        }
        if (isall == 1) {
            if ([self.isFromSale isEqualToString:@"0"]) {
                [cell relayoutCellWithIsAll:@"1" andClassChoose:self.rightNowClassModel andArray:self.schoolNameArr];
            }else{
            [cell relayoutCellWithIsAll:@"1"];
            }
        }else{
            if ([self.isFromSale isEqualToString:@"0"]) {
                [cell relayoutCellWithIsAll:@"0" andClassChoose:self.rightNowClassModel andArray:self.schoolNameArr];
            }else{
                [cell relayoutCellWithIsAll:@"0"];
            }
        }
        //全选
        __weak typeof(self) weak_self = self;
        
        cell.callAll = ^(NSString *str) {
            
            if ([str isEqualToString:@"1"]) {//当前处于全选状态 要改为非全选
                for (ChildModel * mod in self.rightNowDataArray) {
                    mod.isSelected = @"0";
                    for (NSMutableDictionary * dic in masterArray) {//查找MASTER 看这个孩子之前有没有参与这个计划
                      NSMutableDictionary * masterDic = [dic objectForKey:@"master"];
                            if ([mod.Id isEqual:[masterDic objectForKey:@"ChildId"]]) {
                            if ([[masterDic objectForKey:@"ProgramId"]isEqual:self.ownModel.Id]) {
                                if ([[masterDic objectForKey:@"Id"]integerValue] >= 0 ) {
                                    mod.isSelected = @"1";
                                }
                                        }
                                    }
                                }
                }
                if ([_isFromSale isEqualToString:@"0"]) {
//                [self showMessage:@"有些孩子数据已经上传，无法取消选择"];
                }
            }else{ //当前处于非全选状态 要改为全选
                for (ChildModel * mod in self.rightNowDataArray) {
                    mod.isSelected = @"1";
                }
            }
            if ([_isFromSale isEqualToString:@"0"]) {
            [weak_self.dataArray replaceObjectAtIndex:weak_self.rightNowInteger withObject:weak_self.rightNowDataArray];
            [weak_self.myTableView reloadData];
            [weak_self.rightView removeFromSuperview];
            [weak_self setRightView];
            }else{
                [weak_self.myTableView reloadData];
                [weak_self.rightView removeFromSuperview];
                [weak_self setRightView];
            }
        };
        
//        选择班级
        cell.callClass = ^{
            [weak_self pressChooseClass];
        };
        
        return  cell;
    }else{
        ChoosePersonCell * cell = [tableView dequeueReusableCellWithIdentifier:@"ChoosePersonCell"];
        if (cell ==nil) {
            cell = [[ChoosePersonCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"ChoosePersonCell"];
        }
        [cell relayoutCellWithModel:self.rightNowDataArray[indexPath.row-1] andIndex:indexPath.row-1];
        ///////
        __weak typeof(self) weak_self = self;
        cell.callChange = ^(NSString *select, NSInteger index) {
            if ([select isEqualToString:@"1"]) {//当前状态为选中  设置取消选中
                ChildModel * mod = weak_self.rightNowDataArray[index];
                mod.isSelected = @"0";
                for (NSMutableDictionary * dic in masterArray) {//查找MASTER 看这个孩子之前有没有参与这个计划
                    NSMutableDictionary * masterDic = [dic objectForKey:@"master"];
                    if ([mod.Id isEqual:[masterDic objectForKey:@"ChildId"]]) {
                        if ([[masterDic objectForKey:@"ProgramId"]isEqual:self.ownModel.Id]) {
                            if ([[masterDic objectForKey:@"Id"]integerValue] >= 0 ) {//id大于0 说明是之前参加的孩子，不能删除
                                mod.isSelected = @"1";
                                [self showMessage:@"该孩子数据已经上传，无法取消"];
                            }
                        }
                    }
                }
                
                
                [weak_self.rightNowDataArray replaceObjectAtIndex:index withObject:mod];
                
                
            }else{//当前状态为未选中  设置为选中
                ChildModel * mod = weak_self.rightNowDataArray[index];
                mod.isSelected = @"1";
                [weak_self.rightNowDataArray replaceObjectAtIndex:index withObject:mod];
            }
            if ([_isFromSale isEqualToString:@"0"]) {
            [weak_self.dataArray replaceObjectAtIndex:weak_self.rightNowInteger withObject:weak_self.rightNowDataArray];
            [weak_self.myTableView reloadData];
            [weak_self.rightView removeFromSuperview];
            [weak_self setRightView];
            }else{
                [weak_self.myTableView reloadData];
                [weak_self.rightView removeFromSuperview];
                [weak_self setRightView];
            }
        };
        
        

        return  cell;
    }
}

//右侧取消选中
-(void)cancelChoose:(UIButton*)sender{
    
    if ([_isFromSale isEqualToString:@"0"]) {
        
    NSMutableArray * masterArray = [NSMutableArray arrayWithArray:[_allDataDictionary objectForKey:@"TestResult"]];
    NSInteger b = 0;
    for (ChildModel * model in self.rightArray) {
        
        if ([model.isSelected isEqualToString:@"1"]) {
            if (b == sender.tag -200){
                model.isSelected = @"0";
                for (NSMutableDictionary * dic in masterArray) {//查找MASTER 看这个孩子之前有没有参与这个计划
                    NSMutableDictionary * masterDic = [dic objectForKey:@"master"];
                    if ([model.Id isEqual:[masterDic objectForKey:@"ChildId"]]) {
                        if ([[masterDic objectForKey:@"ProgramId"]isEqual:self.ownModel.Id]) {
                            if ([[masterDic objectForKey:@"Id"]integerValue] >= 0 ) {//id大于0 说明是之前参加的孩子，不能删除
                                model.isSelected = @"1";
                                [self showMessage:@"该孩子数据已经上传，无法取消"];
                            }
                        }
                    }
                }

            }
            b +=1 ;
        }
    }
    if ([_isFromSale isEqualToString:@"0"]) {
    [self.dataArray replaceObjectAtIndex:self.rightNowInteger withObject:self.rightNowDataArray];
    
    [self.myTableView reloadData];
    [self.rightView removeFromSuperview];
    [self setRightView];
    }else{
        [self.myTableView reloadData];
        [self.rightView removeFromSuperview];
        [self setRightView];
    }
    }else{
        NSMutableArray * masterArray = [NSMutableArray arrayWithArray:[_allDataDictionary objectForKey:@"TestResult"]];
        NSInteger b = 0;
        for (ChildModel * model in self.rightNowDataArray) {
            
            if ([model.isSelected isEqualToString:@"1"]) {
                if (b == sender.tag -200){
                    model.isSelected = @"0";
                    for (NSMutableDictionary * dic in masterArray) {//查找MASTER 看这个孩子之前有没有参与这个计划
                        NSMutableDictionary * masterDic = [dic objectForKey:@"master"];
                        if ([model.Id isEqual:[masterDic objectForKey:@"ChildId"]]) {
                            if ([[masterDic objectForKey:@"ProgramId"]isEqual:self.ownModel.Id]) {
                                if ([[masterDic objectForKey:@"Id"]integerValue] >= 0 ) {//id大于0 说明是之前参加的孩子，不能删除
                                    model.isSelected = @"1";
                                    [self showMessage:@"该孩子数据已经上传，无法取消"];
                                }
                            }
                        }
                    }
                    
                }
                b +=1 ;
            }
        }
        if ([_isFromSale isEqualToString:@"0"]) {
            [self.dataArray replaceObjectAtIndex:self.rightNowInteger withObject:self.rightNowDataArray];
            
            [self.myTableView reloadData];
            [self.rightView removeFromSuperview];
            [self setRightView];
        }else{
            [self.myTableView reloadData];
            [self.rightView removeFromSuperview];
            [self setRightView];
        }
    }
}

//选取班级视图
-(void)pressChooseClass{
    //蒙版
    UIWindow * window = [UIApplication sharedApplication].keyWindow;
    _backView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    _backView.backgroundColor = [UIColor clearColor];
    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapCancel)];
    [_backView addGestureRecognizer:tap];
//    _backView.alpha = 0.52;
    [window addSubview:_backView];
    [window bringSubviewToFront:self.newwView];
    self.newwView.hidden =NO;
}

-(void)tapCancel{
    self.newwView.hidden =YES;
    [_backView removeFromSuperview];
}
//确定选取班级
-(void)chooseClassWithSender:(UIButton*)sender{
    self.newwView.hidden =YES;
    [_backView removeFromSuperview];
    //人员以班级为单位筛选
    //默认班级
    self.rightNowClassModel = self.schoolNameArr[sender.tag-1000];
    self.rightNowDataArray = self.dataArray[sender.tag-1000];
    self.rightNowInteger = sender.tag-1000;
    [self.myTableView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.view.mas_left).with.offset(75*AutoScaleHorizontal);
        make.top.mas_equalTo(self.view.mas_top).with.offset(20*AutoScaleVertical);
        if ([_isFromSale isEqualToString:@"0"]) {
            make.size.mas_equalTo(CGSizeMake(200*AutoScaleHorizontal, (70*self.rightNowDataArray.count+205)*AutoScaleHorizontal));
        }else{
            make.size.mas_equalTo(CGSizeMake(200*AutoScaleHorizontal, (70*self.rightNowDataArray.count+150)*AutoScaleHorizontal));
        }
        
    }];
    [self.myTableView removeFromSuperview];
    [self.rightView removeFromSuperview];
    [self creatUI];
}
#pragma mark 左右导航栏按钮方法
-(void)leftBarBtnClicked{
    NSLog(@"左按钮");
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)rightBarBtnClicked{
    NSLog(@"确定");
    if ([_isFromSale isEqualToString:@"0"]) {
    //更新数据源
    NSUserDefaults * user = [NSUserDefaults standardUserDefaults];
    NSMutableArray * arr = [_allDataDictionary objectForKey:@"TestResult"];
    NSMutableArray * newModelArr = [NSMutableArray array];
    for (NSMutableArray * arra in self.dataArray) {
        for (ChildModel * model in arra) {
            [newModelArr addObject:model];
        }
    }
    
    for (ChildModel * model in newModelArr) {
        if ([model.isSelected isEqualToString:@"1"]) {//当模型被选中
            NSInteger isExists = 0 ;//用来判断模型是否存在MASTER 里
    for (NSMutableDictionary * dict in arr.reverseObjectEnumerator) {
        NSMutableDictionary * dic = [dict objectForKey:@"master"];
                  if ([[dic objectForKey:@"ChildId"]isEqual:model.Id]) {
             if ([[dic objectForKey:@"ProgramId"]isEqual:self.ownModel.Id]) {
//            NSLog(@"此孩子以前就参与了计划:%@",model.ChildName);
                 isExists += 1;                        //若以前就在，说明不用创建新的MASTER
                                                                            }
                                                                        }
                                                                     }
            if (isExists ==0) {
                    NSMutableDictionary * TestResultDic= [[NSMutableDictionary alloc]init];//新加的孩子master给负ID
                    NSMutableDictionary * masterDic = [[NSMutableDictionary alloc]init];
                    [masterDic setObject:model.Birthday forKey:@"Birthday"];
                NSString * birthStr = [model.Birthday substringWithRange:NSMakeRange(0, 10)];
                NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
                [dateFormatter setDateFormat:@"yyyy-MM-dd"];
                NSDate *birthDate = [dateFormatter dateFromString:birthStr];
                NSString * realAge = [self dateToOld:birthDate];
                NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
                [numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
                NSNumber *numrealAge = [numberFormatter numberFromString:realAge];
                if ([numrealAge integerValue]<3) {
                    [masterDic setObject:@3 forKey:@"Age"];
                }else{
                [masterDic setObject:numrealAge forKey:@"Age"];
                }
                    [masterDic setObject:model.Id forKey:@"ChildId"];
                    [masterDic setObject:model.ChildName forKey:@"ChildName"];
                    [masterDic setObject:model.ClassId forKey:@"ClassId"];
                    [masterDic setObject:model.Name forKey:@"ClassName"];
                    [masterDic setObject:model.Gender forKey:@"Gender"];
                    [masterDic setObject:self.ownModel.Id forKey:@"ProgramId"];
                    [masterDic setObject:model.ServiceUnitId forKey:@"ServiceUnitId"];
                    //给一个新的负数ID
                    NSInteger  creatId = [[user objectForKey:@"CreatMasterId"]integerValue]-1;
                    NSNumber * creatMasterId = [NSNumber numberWithInt:creatId];
                    [user setObject:creatMasterId forKey:@"CreatMasterId"];
                    [masterDic setObject:creatMasterId forKey:@"Id"];
                    
                    [TestResultDic setObject:masterDic forKey:@"master"];
                
                //给他一个空的项目数组
                NSMutableArray * detailNewArr = [[NSMutableArray alloc]init];
                [TestResultDic setObject:detailNewArr forKey:@"detailList"];
                
                    [arr addObject:TestResultDic];
                              }
        }else{//当模型没有选中时， 遍历数据源，删除添加。
            for (NSMutableDictionary * dict in arr.reverseObjectEnumerator) {
                NSMutableDictionary * dic = [dict objectForKey:@"master"];
                if ([[dic objectForKey:@"ChildId"]isEqual:model.Id]) {
                    if ([[dic objectForKey:@"ProgramId"]isEqual:self.ownModel.Id]) {
                        if ([[dic objectForKey:@"Id"]integerValue] <0) {//原有已经上传的参加计划的孩子不能删除 只能删除新添加的MASTER 故不用做处理
                            [arr removeObject:dict];
                            
                        }
                        
                    }
                }
                                                                            }
             }
        
                                            }
    
    [_allDataDictionary removeObjectForKey:@"TestResult"];
    [_allDataDictionary setObject:arr forKey:@"TestResult"];
    NSData * data = [NSJSONSerialization dataWithJSONObject:_allDataDictionary options:NSJSONWritingPrettyPrinted error:nil];
    NSString * allStr = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
        NSLog(@"%@",allStr);
    [user removeObjectForKey:@"AllData"];
    [user setObject:allStr forKey:@"AllData"];
    [user synchronize];

    [self showMessage:@"修改成员成功"];
    }
    

    else{//从营销场景  进入的数据确定保存(此处只是单利保存了本次新测试的孩子ID ，并没有对本地数据造成改变，营销场景的数据需要到下一界面去改变 例如添加孩子和改成绩。)
        //更新数据源
        NSMutableDictionary * finalDic = [[NSMutableDictionary alloc]init];
        NSMutableArray * saleFinalArray = [[NSMutableArray alloc]init];//本地存储最终确定的计划测试人
        NSUserDefaults * user = [NSUserDefaults standardUserDefaults];
        NSMutableArray * arr = [_allDataDictionary objectForKey:@"TestResult"];
        for (ChildModel * model in self.rightNowDataArray) {
            if ([model.isSelected isEqualToString:@"1"]) {
            for (NSMutableDictionary * dict in arr) {
                NSMutableDictionary * dic = [dict objectForKey:@"master"];
                if ([[dic objectForKey:@"Id"]isEqual:model.Id]) {  //由于营销计划的孩子  CHILDID 都是 0 所以此处直接用ID判断
                    [saleFinalArray addObject:[dic objectForKey:@"Id"]];
                    [finalDic setObject:saleFinalArray forKey:@"finalSaleDic"];//营销场景最终确定的人
                }
                }
            }
        }
            NSData * dataDic = [NSJSONSerialization dataWithJSONObject:finalDic options:NSJSONWritingPrettyPrinted error:nil];
            NSString * FS = [[NSString alloc]initWithData:dataDic encoding:NSUTF8StringEncoding];
            //
            [user removeObjectForKey:@"finalSaleDic"];
            [user setObject:FS forKey:@"finalSaleDic"];
            [user synchronize];
        NSLog(@"%@",[user objectForKey:@"finalSaleDic"]);
        
        [_allDataDictionary removeObjectForKey:@"TestResult"];
        [_allDataDictionary setObject:arr forKey:@"TestResult"];
        NSData * data = [NSJSONSerialization dataWithJSONObject:_allDataDictionary options:NSJSONWritingPrettyPrinted error:nil];
        NSString * allStr = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
        //
        [user removeObjectForKey:@"AllData"];
        [user setObject:allStr forKey:@"AllData"];
        [user synchronize];
        
        [self showMessage:@"修改成员成功"];
    }
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
